import { QueryConfig } from 'pg'
import { container } from 'tsyringe'
import { usePgClient, IPgClientCallback } from '@sker/pdo';
import { HttpError, useEntityManager } from '@sker/core';
import { SysAddon } from '@sker/entities';

export function pdo<T>(cb: IPgClientCallback<T>) {
    return usePgClient(container, cb)
}

export function pdo_get<T>(sql: QueryConfig) {
    return pdo(async (db, pool) => {
        const { rows } = await pool.query(sql)
        return rows.length > 0 ? rows[0] : null;
    })
}

export function pdo_fetch() { }

export const useAddonSetting = (name: string) => {
    return useEntityManager(async m => {
        const one = await m.findOne(SysAddon, { where: { name: name } })
        if (!one) throw new HttpError(`${name}不存在`)
        return one.setting;
    })
}